#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/1/29 9:53
# @Author : wxc
# @File : yun_daka.py
# @Desc : 自动打卡脚本
import os

import premailer.premailer
import requests
import yagmail
import schedule
import time
import yaml
import re
# 忽略警告
requests.packages.urllib3.disable_warnings()


class Yun_data(object):
    def __init__(self, name, psswd, address):
        self.headers = {
            "User-Agent": 'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, '
                          'like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 '
        }
        self.login_url = 'https://nco.zjgsu.edu.cn/login'
        self.tianxie_url = 'https://nco.zjgsu.edu.cn/'
        self.name = str(name)
        self.psswd = str(psswd)
        self.uuid = ''
        self.address = address
        self.session = requests.session()

    def run(self):
        """
        程序主入口
        :return:
        """
        self.get_uuid()
        self.login()
        resp = self.submit()
        self.to_html(resp)

    def get_uuid(self):
        resp = self.session_get(url=self.login_url)
        # 通过正则获得uuid
        self.uuid = re.findall('var uuid = "(.*?)";', resp.text)[0]

    def login(self):
        """
        通过post请求进行登陆
        如果我不登陆直接构造cookie访问https://nco.zjgsu.edu.cn/而没有进行登陆的话是不行的，即使我的cookie是对的
        后台有做标记,判断这个cookie有没有login过
        :return:
        """

        cookies = {}
        cookies['_ncov_uuid'] = self.uuid
        cookies['_ncov_username'] = self.name
        cookies['_ncov_psswd'] = self.psswd
        requests.utils.add_dict_to_cookiejar(self.session.cookies, cookies)
        data = {
            "name": self.name,
            "psswd": self.psswd
        }
        self.session_post(url=self.login_url, data=data)
        return


    def submit(self):
        """
        通过post请求提交数据
        :return:
        """
        # 封装param参数
        form_data = {
            'uuid': self.uuid,
            'locationInfo': self.get_location_info(),
            'currentResd': self.address,
            'fromHbToZjDate': '',
            'fromHbToZj': 'C',
            'fromWtToHzDate': '',
            'fromWtToHz': 'B',
            'meetDate': '',
            'meetCase': 'C',
            'travelDate': '',
            'travelCase': 'D',
            'medObsvReason': '',
            'medObsv': 'B',
            'belowCaseDesc': '',
            'belowCase': 'D',
            'temperature': '',
            'notApplyReason': '',
            'hzQRCode': 'A',
            'specialDesc': ''
        }
        return self.session_post(url=self.tianxie_url, data=form_data)

    def get_location_info(self):
        """
        发送请求获得locationInfo值
        :return: locationInfo
        """
        address_find_url = 'https://ip.ws.126.net/ipquery'
        text = requests.get(url=address_find_url, verify=False).text
        result = re.findall('var lo="(.*?)", lc="(.*?)";', text)
        # [('浙江省', '杭州市')]
        return result[0][0] + result[0][1]

    def to_html(self, resp):
        with open('./yundaka.html', 'wb') as f:
            f.write(resp.content)

    def session_get(self, url, data=None):
        if data is None:
            data = {}
        return self.session.get(url=url, data=data, headers=self.headers, verify=False)

    def session_post(self, url, data=None):
        if data is None:
            data = {}
        return self.session.post(url=url, data=data, headers=self.headers, verify=False)


class SendEmail(object):
    def __init__(self, user, password, host='smtp.qq.com'):
        self.user = user
        self.password = password
        self.host = host
        self.content = []

    def send(self, send_content="", title='python自动化云战役打卡', user=""):
        yag = yagmail.SMTP(user=self.user, password=self.password, host=self.host)
        self.content.append(send_content)
        try:
            if len(self.content) == 1:
                self.content = self.content[0]
            yag.send(to=user, subject=title, contents=yagmail.raw(self.content))
            print('发送成功')
        except RuntimeError as e:
            print(e)

    def expansion(self, expansion_url):
        """

        :param expansion_url: 附件url
        :return:
        """
        self.content.append(expansion_url)


def filter_html(content):
    """
    对html进行过滤
    :return: filter 后的 content
    """
    content = content.replace('<link rel="stylesheet" href="/assets/css/styles.css">', '')
    content = content.replace('\n', ' ').replace('\t', ' ').replace('\r', ' ')
    return content


def read_html(address):
    with open(address, "r", encoding="utf-8") as f:
        content = f.read()
    return content


def parse_yaml(yaml_address):
    with open(yaml_address, 'r', encoding='utf-8') as ymlfile:
        yaml_str = yaml.load(ymlfile, Loader=yaml.SafeLoader)
    return yaml_str


def entrace():
    """
    主程序入口
    :return:
    """
    json_data = parse_yaml('./config.yaml')
    if not check_email(json_data):
        return
    Yun_data(json_data['name'], json_data['psswd'], json_data['address']).run()
    # 安全原因这是伪邮箱授权码
    email = SendEmail('962447907@qq.com', 'xxxxxxx')
    content = read_html('./yundaka.html')
    content = filter_html(content)
    email.send(send_content=content, user=json_data['qqEmail'])


def check_email(json_data):
    ex_email = re.compile(r'^[1-9][0-9]{4,10}@qq\.com')
    if not re.match(ex_email, json_data['qqEmail']):
        print("邮箱不合法!")
        return False
    return True


if __name__ == '__main__':
    os.system("cls")
    print("\t" + "=" * 91)
    print('\t|\t\t 云战役自动打卡脚本')
    print('\t|\t\t 每天早上10点半自动云战役打卡并将结果发送到你的邮箱')
    print('\t|\t\t 使用方法:')
    print('\t|\t\t - 打开同目录下config.yaml文件，打不开的可以选择记事本')
    print('\t|\t\t - 按照注释修改这4个值即可')
    print('\t|\t\t - 切记不要关闭该脚本，每天10点半前需要运行该脚本，否则不生效')
    print("\t" + "=" * 91)
    print("\t{:^90}".format("author: wxc"))
    print("\t{:^90}".format("博客: https://blog.csdn.net/qq_44675969/article/details/112212736"))
    schedule.every().day.at("10:30:00").do(entrace)
    print("脚本开始运行.....")
    print("请确认yaml文件中值是否已经修改.....")
    while True:
        try:
            schedule.run_pending()
        except Exception as e:
            print(e)
        time.sleep(60)
